import router,{asyncRoutes} from '@/router'
import store from '@/store'
import 'nprogress/nprogress.css'
import NProgress from 'nprogress'

import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']// 白名单
router.beforeEach(async(to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  const token = store.state.user.token
  console.log('全局前置路由守卫', token)
  console.log(to, from)
  next()
  if (token) {
    if (to.path === '/login') {
      console.log('已经登录,不能去主页,跳转首页')
      next('/')
      NProgress.done()
    } else {
      console.log('已经登录不是去登录页,放行')
      if (!store.state.user.userInfo.userId) {
      const menus = await store.dispatch('user/setUserInfo')
      console.log(menus,'menusmenus')
      console.log(asyncRoutes,'asyncRoutes')
      // 根据本用户实际权限menu去 asyncRoutes 中做过率,选出本用户能访问的页面
      const filterRoutes = asyncRoutes.filter(route => {
        const routeName = route.children[0].name
        return menus.includes(routeName)
      })
      filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 动态添加可以访问的路由设置
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList',filterRoutes)
        // 解决刷新出现白屏bug
        next({
          ...to, // next({...to})的目的,是保证路由添加完了在进入页面(重新进入一次)
          replace:true // 重进一次不保留重复历史
        })
      }else{
        next()
      }

      
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('你没有登录,转到登录页')
      next('/login')
      NProgress.done()
    }
  }
  console.log(token, from.path, '----->', to.path)
})

router.afterEach(() => {
  NProgress.done()
})
